/*
 * @Descripttion: 
 * @version: 
 * @Author: 刘冰见
 * @Date: 2024-10-08 23:18:31
 * @LastEditors: 刘冰见
 * @LastEditTime: 2025-06-29 11:48:17
 */

import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:sousuoapp/common/auth.dart';
import 'package:sousuoapp/https/order_controller.dart';
import 'package:sousuoapp/models/orderItem.dart';
import 'package:widgets_easier/widgets_easier.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_slider_drawer/flutter_slider_drawer.dart';
import 'package:panara_dialogs/panara_dialogs.dart';

class OrderScreen extends StatefulWidget {
  /// Constructs a [OrderScreen]
  const OrderScreen({super.key});
  @override
  State<OrderScreen> createState() => _OrderScreenState();
}

class PhoneValidator {
  // 判断是否为中国大陆手机号
  static bool isChinaPhoneNumber(String phone) {
    final regExp = RegExp(r'^1[3-9]\d{9}$');
    return regExp.hasMatch(phone);
  }

  // 判断是否为香港手机号
  static bool isHongKongPhoneNumber(String phone) {
    // 香港手机号码 8 位数，格式为：6/9 开头 + 7 位任意数
    final regExp = RegExp(r'^[6|9]\d{7}$');
    return regExp.hasMatch(phone);
  }
}

class _OrderScreenState extends State<OrderScreen> {
  var customBorder = OutlineInputBorder(
      borderRadius: BorderRadius.circular(24),
      borderSide: const BorderSide(style: BorderStyle.solid, width: 1));
  var searchStr = '';
  List<Orderitem> orderList = <Orderitem>[];
  _getOrderListByPhoneHttp(str) async {
    EasyLoading.show(status: '数据加载中...', maskType: EasyLoadingMaskType.black);

    // ignore: prefer_typing_uninitialized_variables
    var temp = <Orderitem>[];
    temp = await OrderController().getOrderList({'user_phone': str});
    EasyLoading.dismiss();
    setState(() {
      if (temp.isNotEmpty) {
        orderList = temp;
      } else {
        orderList = [];
      }
    });
  }

  _getOrderListByOrderHttp(str) async {
    // ignore: prefer_typing_uninitialized_variables
    EasyLoading.show(status: '数据加载中...', maskType: EasyLoadingMaskType.black);
    var temp = <Orderitem>[];
    temp = await OrderController().getOrderList({'o_order_code': str});
    EasyLoading.dismiss();
    setState(() {
      if (temp.isNotEmpty) {
        orderList = temp;
      }
    });
  }

  _cancelOrderHttp(data) async {
    var res = await OrderController().cancelDeletOrder(data);
    return res;
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var userName = GetStorage().read('username') ?? '';
    var h_real_name = GetStorage().read('h_real_name') ?? '';
    var h_user_info = GetStorage().read('h_user_info') ?? '';
    final auth = Provider.of<Auth>(context);

    if (auth.isAuthenticated) {
      context.replace('/login');
    }

    return FlutterEasyLoading(
      child: Scaffold(
          body: SliderDrawer(
              slider: Container(
                padding: const EdgeInsets.all(20),
                color: Colors.black87,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(
                      height: 100,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.people,
                          color: Colors.amber[100],
                        ),
                        const SizedBox(
                          width: 40,
                        ),
                        Text(
                          '$h_real_name',
                          style: const TextStyle(color: Colors.white),
                        ),
                      ],
                    ),
                    const SizedBox(
                      height: 40,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.phone,
                          color: Colors.amber[100],
                        ),
                        const SizedBox(
                          width: 40,
                        ),
                        Text(
                          '$userName',
                          style: const TextStyle(color: Colors.white),
                        ),
                      ],
                    ),
                    const SizedBox(
                      height: 40,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.local_car_wash,
                          color: Colors.amber[100],
                        ),
                        const SizedBox(
                          width: 40,
                        ),
                        Text(
                          '$h_user_info',
                          style: const TextStyle(color: Colors.white),
                        ),
                      ],
                    ),
                    const SizedBox(
                      height: 40,
                    ),
                    Center(
                      child: SemanticButton(
                        text: '退出登录',
                        type: SemanticEnum.danger,
                        onTap: () => PanaraConfirmDialog.show(
                          context,
                          title: "你确定要退出登录吗",
                          message: "",
                          noImage: true,
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          onTapCancel: () {
                            Navigator.pop(context);
                            // Navigator.of(context).pop();
                          },
                          barrierDismissible:
                              false, // optional parameter (default is true)

                          onTapConfirm: () async {
                            Navigator.pop(context);
                            auth.logout();
                            context.replace('/login');
                          },
                          panaraDialogType: PanaraDialogType.warning,
                        ),
                      ),
                    )
                  ],
                ),
              ),
              appBar: SliderAppBar(
                  title: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  const Image(
                      width: 40,
                      height: 40,
                      alignment: Alignment.center,
                      image: AssetImage('assets/images/logo.png')),
                  Text('$userName', style: const TextStyle(fontSize: 16)),
                ],
              )),
              child: Column(
                children: [
                  Padding(
                      padding: const EdgeInsets.only(
                          left: 20, top: 0, right: 20, bottom: 0),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(
                              height: 36,
                              width: 300,
                              child: TextField(
                                style: const TextStyle(
                                    color: Colors.black87, height: 1.2),
                                maxLines: 1,
                                minLines: 1,
                                onChanged: (value) {
                                  setState(() {
                                    searchStr = value;
                                  });
                                },
                                decoration: InputDecoration(
                                    hintText: '请输入手机号或者订单号',
                                    border: customBorder,
                                    filled: false,
                                    fillColor: const Color.fromARGB(
                                        255, 182, 170, 170),
                                    focusColor: const Color.fromARGB(
                                        255, 255, 255, 255),
                                    hoverColor: const Color.fromARGB(
                                        255, 182, 170, 170),
                                    hintStyle: const TextStyle(
                                        fontSize: 14,
                                        color: Color.fromARGB(255, 0, 0, 0)),
                                    contentPadding: const EdgeInsets.symmetric(
                                        vertical: 0, horizontal: 16)),
                              )),
                          IconButton(
                            icon: const Icon(
                              Icons.search,
                              size: 24,
                            ),
                            onPressed: () {
                              if (searchStr.isEmpty) {
                                EasyLoading.showToast('请输入手机号或者订单号');
                                return;
                              }
                              if (PhoneValidator.isChinaPhoneNumber(
                                  searchStr)) {
                                _getOrderListByPhoneHttp(searchStr);
                              } else {
                                _getOrderListByOrderHttp(searchStr);
                              }
                              print(searchStr);
                            },
                          ),
                        ],
                      )),
                  Expanded(
                      child: orderList.isNotEmpty
                          ? ListView.builder(
                              itemCount: orderList.length,
                              itemBuilder: (context, index) {
                                var orderStatusText = orderList[index]
                                            .oStatus ==
                                        -1
                                    ? '已取消'
                                    : orderList[index].oStatus == 0
                                        ? '待支付'
                                        : orderList[index].oStatus == 1
                                            ? '待取镜'
                                            : orderList[index].oStatus == 2
                                                ? '待还镜'
                                                : orderList[index].oStatus == 3
                                                    ? '已完成'
                                                    : '';
                                var tagStaus = orderList[index].oStatus == -1
                                    ? SemanticEnum.secondary
                                    : orderList[index].oStatus == 0
                                        ? SemanticEnum.info
                                        : orderList[index].oStatus == 1
                                            ? SemanticEnum.success
                                            : orderList[index].oStatus == 2
                                                ? SemanticEnum.warning
                                                : SemanticEnum.danger;
                                var isRefont = orderList[index].oIsRefund == -1
                                    ? '已退款'
                                    : orderList[index].oIsRefund == 1
                                        ? '退款中'
                                        : '#';
                                var doType = (orderList[index].oStatus == 0 ||
                                        orderList[index].oStatus == 1)
                                    ? 'cancel'
                                    : (orderList[index].oStatus == 2 ||
                                            orderList[index].oStatus == 3)
                                        ? 'refund'
                                        : '';

                                return Padding(
                                  padding: const EdgeInsets.all(10),
                                  child: Card(
                                    child: Padding(
                                      padding: const EdgeInsets.all(10),
                                      child: Column(
                                        children: [
                                          Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text.rich(TextSpan(children: [
                                                const TextSpan(text: '订单编号：'),
                                                TextSpan(
                                                    text: orderList[index]
                                                        .oOrderCode,
                                                    style: const TextStyle(
                                                        fontSize: 14))
                                              ])),
                                              Tag(
                                                orderStatusText,
                                                type: tagStaus,
                                                size: SizeEnum.small,
                                                theme: TagThemeEnum.dark,
                                              )
                                            ],
                                          ),
                                          const SizedBox(
                                            height: 10,
                                          ),
                                          const Divider(
                                            height: 2,
                                          ),
                                          const SizedBox(
                                            height: 10,
                                          ),
                                          Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text.rich(TextSpan(children: [
                                                const TextSpan(text: '所属系统：'),
                                                TextSpan(
                                                    text: orderList[index].area)
                                              ])),
                                            ],
                                          ),
                                          const SizedBox(
                                            height: 3,
                                          ),
                                          Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Expanded(
                                                child: Text.rich(
                                                    TextSpan(children: [
                                                  const TextSpan(text: '场地名称：'),
                                                  TextSpan(
                                                      style: const TextStyle(
                                                          overflow: TextOverflow
                                                              .ellipsis),
                                                      text: orderList[index]
                                                          .fFieldName)
                                                ])),
                                              ),
                                            ],
                                          ),
                                          Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text.rich(TextSpan(children: [
                                                const TextSpan(text: '已取镜数量:'),
                                                TextSpan(
                                                    text:
                                                        '${orderList[index].num}')
                                              ])),
                                              Text.rich(TextSpan(children: [
                                                const TextSpan(text: '已还镜数量：'),
                                                TextSpan(
                                                    text:
                                                        '${orderList[index].fNum.toInt()}')
                                              ])),
                                            ],
                                          ),
                                          const SizedBox(
                                            height: 3,
                                          ),
                                          Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text.rich(TextSpan(children: [
                                                const TextSpan(text: '订单眼镜数量:'),
                                                TextSpan(
                                                    text:
                                                        '${orderList[index].oGlassesNum}')
                                              ])),
                                              Text.rich(TextSpan(children: [
                                                const TextSpan(text: '金额:'),
                                                TextSpan(
                                                    text:
                                                        '${orderList[index].oMoney}')
                                              ])),
                                            ],
                                          ),
                                          const SizedBox(
                                            height: 3,
                                          ),
                                          Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text.rich(TextSpan(children: [
                                                const TextSpan(text: '下单时间:'),
                                                TextSpan(
                                                    text: orderList[index]
                                                        .oStartTime)
                                              ])),
                                              Text.rich(TextSpan(children: [
                                                const TextSpan(text: '是否退款:'),
                                                TextSpan(
                                                    text: isRefont,
                                                    style: TextStyle(
                                                        color: orderList[index]
                                                                    .oIsRefund ==
                                                                -1
                                                            ? Colors.green[300]
                                                            : Colors.pink[200]))
                                              ])),
                                            ],
                                          ),
                                          const SizedBox(
                                            height: 10,
                                          ),
                                          const Divider(
                                            height: 2,
                                          ),
                                          const SizedBox(
                                            height: 10,
                                          ),
                                          !(orderList[index].oIsRefund == 1 ||
                                                  orderList[index].oIsRefund ==
                                                      -1 ||
                                                  orderList[index].oStatus ==
                                                      -1)
                                              ? Row(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.end,
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.end,
                                                  children: [
                                                    SemanticButton(
                                                      text: (orderList[index]
                                                                      .oStatus ==
                                                                  0 ||
                                                              orderList[index]
                                                                      .oStatus ==
                                                                  1)
                                                          ? '取消订单'
                                                          : (orderList[index]
                                                                          .oStatus ==
                                                                      2 ||
                                                                  orderList[index]
                                                                          .oStatus ==
                                                                      3)
                                                              ? '退款'
                                                              : '退款中~~',
                                                      type:
                                                          SemanticEnum.warning,
                                                      onTap: () =>
                                                          PanaraConfirmDialog
                                                              .show(
                                                        context,
                                                        noImage: true,
                                                        title:
                                                            "你确定要${(orderList[index].oStatus == 0 || orderList[index].oStatus == 1) ? '取消订单' : (orderList[index].oStatus == 2 || orderList[index].oStatus == 3) ? '退款' : ''}该订单吗?",
                                                        message: "",
                                                        confirmButtonText: "确定",
                                                        cancelButtonText: "取消",
                                                        onTapCancel: () {
                                                          EasyLoading.dismiss();
                                                          Navigator.pop(
                                                              context);
                                                          // Navigator.of(context)
                                                          //     .pop();
                                                        },
                                                        barrierDismissible:
                                                            false, // optional parameter (default is true)

                                                        onTapConfirm: () async {
                                                          Navigator.pop(
                                                              context);
                                                          EasyLoading.show(
                                                              status:
                                                                  '数据加载中...',
                                                              maskType:
                                                                  EasyLoadingMaskType
                                                                      .black);
                                                          var res =
                                                              await _cancelOrderHttp({
                                                            'o_order_code':
                                                                orderList[index]
                                                                    .oOrderCode,
                                                            'area':
                                                                orderList[index]
                                                                    .area,
                                                            'do_type': doType
                                                          });
                                                          EasyLoading.dismiss();
                                                          if (res['code'] ==
                                                              '1000') {
                                                            EasyLoading
                                                                .showToast(
                                                                    '操作成功');
                                                            setState(() {
                                                              orderList[index]
                                                                  .oIsRefund = 1;
                                                            });
                                                          } else {
                                                            EasyLoading.showToast(
                                                                '操作失败，请稍后重试');
                                                          }
                                                          EasyLoading.dismiss();
                                                        },
                                                        panaraDialogType:
                                                            PanaraDialogType
                                                                .warning,
                                                      ),
                                                    ),
                                                  ],
                                                )
                                              : const Row(
                                                  children: [],
                                                ),
                                        ],
                                      ),
                                    ),
                                  ),
                                );
                              })
                          : const Center(
                              child: Image(
                                  width: 200,
                                  height: 200,
                                  image: AssetImage(
                                      'assets/images/no-result.png')),
                            ))
                ],
              ))),
    );
  }
}
